package com.meirengu.webview.controller;

import com.meirengu.webview.utils.ConfigUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;


/**
 * 生成带简单运算(加、减)的验证码
 */
@Controller
@RequestMapping("captch")
public class CaptchaServlet {

    private static final long serialVersionUID = 5581444867349884055L;

    private static final Random random = new Random();


    @RequestMapping(value = "captch")
    public void captch(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        String code = drawImg(output, request);
        ServletOutputStream out = response.getOutputStream();
        output.writeTo(out);

    }


    private String drawImg(ByteArrayOutputStream output, HttpServletRequest request) {
        String code = createEquation();
//		code="111111";
        int width = 70;
        int height = 25;
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Font font = new Font("Times New Roman", Font.PLAIN, 20);
        Graphics2D g = bi.createGraphics();
        g.setFont(font);
        Color color = new Color(66, 2, 82);
        g.setColor(color);
        g.setBackground(new Color(226, 226, 240));
        g.clearRect(0, 0, width, height);
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(code, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = y - ascent;
        g.drawString(code, (int) x, (int) baseY);
        g.dispose();
        try {
            Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
            ImageWriter writer = (ImageWriter) writers.next();
            String fileName = ConfigUtil.getConfig("LOG_HOME") + File.separator + "a.jpg";
            File file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            /*long timeMillis = System.currentTimeMillis();*/
            /*File f = new File("D:\\myproduct\\acquirecustomer\\webview\\src\\main\\java\\com\\meirengu\\webview\\jpg\\"+timeMillis+".jpg");*/
            ImageOutputStream ios = ImageIO.createImageOutputStream(file);
            writer.setOutput(ios);
            writer.write(bi);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 生成运算式
     *
     * @param
     * @return
     */
    private String createEquation() {
        // 定义数组存放加减二个运算符
        char[] arr = {'+', '-'};

        // 生成10以内的随机整数num1
        int num1 = random.nextInt(10);

        // 生成一个0-2之间的随机整数operate
        int operate = random.nextInt(2);

        // 生成10以内的随机整数num1
        int num2 = random.nextInt(10);

        // 避免出现除数为0的情况
        if (num1 < num2) {
            int temp = num1;
            num1 = num2;
            num2 = temp;
        }

        // 运算结果
        int captchaNo = 0;

        // 假定position值0/1分别代表”+”,”-”，计算前面操作数的运算结果
        switch (operate) {
            case 0:
                captchaNo = num1 + num2;
                break;
            case 1:
                captchaNo = num1 - num2;
                break;
        }

        return num1 + " " + arr[operate] + " " + num2;
    }

}

